import { defineStore } from 'pinia'
import { ref, computed } from 'vue'

export const useUserStore = defineStore('user', () => {
  // 状态
  const userInfo = ref({
    id: null,
    username: '',
    name: '',
    avatar: '',
    role: '',
    department: '',
    permissions: []
  })

  const token = ref(localStorage.getItem('token') || '')
  const isLoggedIn = computed(() => !!token.value)

  // 登录
  const login = async (loginData) => {
    try {
      // 验证账号密码
      if (loginData.username !== 'admin' || loginData.password !== 'admin123') {
        return { success: false, error: '用户名或密码错误' }
      }

      // 模拟登录成功
      const mockUser = {
        id: 1,
        username: loginData.username,
        name: '地府主簿',
        avatar: '/avatars/judge.png',
        role: 'admin',
        department: '地府管理司',
        permissions: ['archives:read', 'archives:write', 'judgment:read', 'judgment:write', 'management:read', 'management:write']
      }

      userInfo.value = mockUser
      token.value = 'mock-jwt-token-' + Date.now()
      localStorage.setItem('token', token.value)
      localStorage.setItem('userInfo', JSON.stringify(mockUser))

      return { success: true, user: mockUser }
    } catch (error) {
      return { success: false, error: error.message }
    }
  }

  // 登出
  const logout = () => {
    userInfo.value = {
      id: null,
      username: '',
      name: '',
      avatar: '',
      role: '',
      department: '',
      permissions: []
    }
    token.value = ''
    localStorage.removeItem('token')
    localStorage.removeItem('userInfo')
  }

  // 初始化用户信息（从localStorage恢复）
  const initUserInfo = () => {
    const savedUserInfo = localStorage.getItem('userInfo')
    if (savedUserInfo) {
      try {
        userInfo.value = JSON.parse(savedUserInfo)
      } catch (error) {
        console.error('Failed to parse user info from localStorage:', error)
        logout()
      }
    }
  }

  // 检查权限
  const hasPermission = (permission) => {
    return userInfo.value.permissions.includes(permission)
  }

  // 更新用户信息
  const updateUserInfo = (newInfo) => {
    userInfo.value = { ...userInfo.value, ...newInfo }
    localStorage.setItem('userInfo', JSON.stringify(userInfo.value))
  }

  return {
    // 状态
    userInfo,
    token,
    isLoggedIn,

    // 方法
    login,
    logout,
    initUserInfo,
    hasPermission,
    updateUserInfo
  }
})
